
package cz.czu.pef.DataModelling.beans;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.richfaces.model.selection.Selection;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cz.czu.pef.DataModelling.Company;
import cz.czu.pef.DataModelling.ejb.api.AbstractWrapperService;

@Component
@ViewScoped
@ManagedBean
public class CompanyBean extends AbstractExtendedTableBean<Company> implements ApplicationContextAware
{
	private static final long serialVersionUID = -3072548005849148994L;

	public static final Logger logger = Logger.getLogger(CompanyBean.class.getName());

	private ApplicationContext applicationContext;

	//@EJB (beanName="companyServiceEJB", mappedName="companyServiceEJB")
	@Autowired
	private AbstractWrapperService<Company> companyServiceEJB;

	//@Autowired
	private Company company;

	protected CompanyBean()
	{
		super();
	}

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
	{
		this.applicationContext = applicationContext;
	}

	@PostConstruct
	public void create()
	{
		company= this.applicationContext.getBean(Company.class);
	}

	public Company getCompany()
	{
		return company;
	}

	public void setCompany(Company company)
	{
		this.company = company;
	}


	public PagingExtendedTableDataModel<Company> getItemsDataModel()
	{
		if (dataModel == null)
		{
			dataModel = new PagingExtendedTableDataModel<Company>(new PagingDataProvider<Company>()
				{

					private static final long serialVersionUID = 5054087821033164847L;

					public Company getItemByKey(Object key)
					{
						String myKey = key.toString();
						logger.finest("getItemByKey():: key=" + myKey);
						return companyServiceEJB.getByStringId(myKey);
					}

					public List<Company> getItemsByRange(int firstRow, int endRow)
					{
						logger.finest("getItemsByRange():: firstRow(" + firstRow + "), endRow(" + endRow + ")");
						return companyServiceEJB.findAllByRangeWithFilterAndSort(firstRow, endRow, getCustomFilterFields(), getCustomSortFields());
					}

					public Object getKey(Company item)
					{
						if (logger.isLoggable(Level.FINEST))
							logger.finest("getKey():: item=" + item);
						return item.getId();
					}

					public int getRowCount()
					{
						Long count = companyServiceEJB.countWithFilter(getCustomFilterFields());
						logger.finest("getRowCount():: count=" + count);
						if (count != null)
							return count.intValue();
						return 0;
					}

				});
		}
		return dataModel;
	}

	public String createNew()
	{
		try
		{
			logger.finest("createNew():: Entry");
			/*
			FacesContext context = FacesContext.getCurrentInstance();
			//Person person = (Person)context.getApplication().evaluateExpressionGet(context, "#{person}", Person.class);
			Person newPerson = (Person) context.getApplication().getExpressionFactory().createValueExpression(context.getELContext(), "#{person}", Person.class).getValue(context.getELContext());
			*/

			logger.info("createNew():: company=" + company);
			if (company != null)
			{
				// persist new person
				companyServiceEJB.merge(company);
			}

			// reset detail form's data
			company = this.applicationContext.getBean(Company.class);

			return null;
		}
		finally
		{
			logger.finest("createNew():: Exit");

		}
	}

	@SuppressWarnings("rawtypes")
	public String removeSelected()
	{
		try
		{
			logger.finest("removeSelected():: Entry");

			Selection selectionForRemoval = getSelection();
			if (selectionForRemoval != null)
			{
				Iterator iter = selectionForRemoval.getKeys();
				while (iter.hasNext())
				{
					Object key = iter.next();
					logger.info("removeSelected():: Removing key=" + key.toString());
					Company company = companyServiceEJB.getByStringId(key.toString());
					if (company != null)
					{
						if (companyServiceEJB.canBeRemoved(company))
							companyServiceEJB.deleteById(key.toString());
						else
							logger.warning("removeSelected():: Cannot remove person because of dependencies: " + company);
					}
					else
						logger.warning("removeSelected():: Cannot remove person because it's already removed: " + company);
				}

				setSelectedItems(new ArrayList<Company>());
			}

			return null;
		}
		finally
		{
			logger.finest("removeSelected():: Exit");
		}
	}

}
